import lib
import os
import time
import datetime
import sys
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
from google.appengine.api import datastore_errors
from model.models import *
from lib import wfMailer

class Processor():
  
  def __init__(self,step=None):
    self.step = step
  
  def canExecute(self,user,company):
    
    self.internal_canExecute(user,company)
    
  
  def internal_canExecute(user,company):
      raise Exception('Operation not allowed')
  
  def execute(self):
    logging.debug("Executing processor")
    try:
      self.internal_execute()
    except Exception,e:
      logging.error(str(e))
    
  
class AuthorizeProjectLeaderProcessor(Processor):
  
      def internal_execute(self):
	  logging.debug("Looking for Project Leader auth")
	  leader = self.step.request.workflow.project.leader
	  wfMailer.WFMailer().mailView(self.step.request,self.step,[leader])

      def internal_canExecute(self,user,company):
	  logging.debug(self.step.request.workflow.project.leader.name)
	  logging.debug(user.name)
	  if self.step.request.workflow.project.leader.key() == user.key():
	    logging.debug("Leader is current user")
	    return True
	  else:
	    logging.debug("Internal execute returns false")
	    raise Exception('User is not project leader')
	  

class AuthorizeAreaResponsibleProcessor(Processor):
      def internal_execute(self):
	  logging.debug("Looking for Area Leader auth")
	  responsibles = PSUser.get(self.step.request.workflow.project.area.responsibles)
	  wfMailer.WFMailer().mailView(self.step.request,self.step,responsibles)
      
      def internal_canExecute(self,user,company):
	 logging.debug(user.key())
	 logging.debug(self.step.request.workflow.project.area.responsibles)
	 
	 if user.key() in self.step.request.workflow.project.area.responsibles:
	   return True
	 else:
	   raise Exception('User is not member of Area responsibles')

class WorkflowDispatcher():
  
  def getProcessorForStep(self,step):
    step_name = str(step.workflow_element.__class__.__name__)
    logging.debug("Looking for processor for step "  + step_name)
    if(step_name == "PSWENotifyProjectLeader"):
      return AuthorizeProjectLeaderProcessor(step) 
    elif(step_name == "PSWENotifyAreaResponsible"):
      return AuthorizeAreaResponsibleProcessor(step)
    return None
  